package com.glsc.ngateway.shortmsg.amqp;

import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.RabbitExcQueConstant;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpSearchDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.common.api.shortmsg.bo.WeixinQueueMsgRequest;
import com.glsc.ngateway.common.base.domain.mysql.gateway.shortmsg.MessageWeixinGroup;
import com.glsc.ngateway.common.base.repo.mysql.gateway.shortmsg.MessageWeixinGroupRepository;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class WeixinMsgReceiver {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MessageWeixinGroupRepository messageWeixinGroupRepository;
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private IFeignLdapService iFeignLdapService;

    @Value("${weixin.queue.url}")
    private String url;

    //  '{ "group": "产品系统需求通知", "content": "测试企业微信触发生产环境发送20220829", "userAccount": "lm,zzp","sysid":"amprod" }'


    //    http://172.16.198.148:8000/glzb-api/zb-warn/b/qywx/robot
//    POST application/json
//    { "key": "xxx", "content": "xxx", "mentionedMobileList": ["189xxxx11132", "133xxxx1111"] }
//
//    curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d
//    '{ "key": "51a4e5c5-f2c5-443e-86c8-a4963facce2f", "content": "测试企业微信触发生产环境发送20220829", "mentionedMobileList": ["18010176323"] }'
//    http://172.16.198.148:8000/glzb-api/zb-warn/b/qywx/robot


    //{"code":0,"data":ture}
    @RabbitListener(queues = {RabbitExcQueConstant.AMPRODUCT_QUEUE_WECHAT_MSG})
    @RabbitHandler
    public void processMessage(Message messageObject) throws IOException, NoSuchFieldException, IllegalAccessException {
        try {
            String message = new String(messageObject.getBody());
            logger.info("gateway.queue.shortmsg.weixin,消息队列收到消息，message receiver:" + message);
            JSONObject msgJsonObject = JSONObject.parseObject(message);
            String group = msgJsonObject.getString("group");
            String sysid = msgJsonObject.getString("sysid");
            MessageWeixinGroup weixinGroup = messageWeixinGroupRepository.findByGroupName(group);
            if (weixinGroup == null) {
                logger.error("企业微信消息队列发送失败,未找到该group！" + group);
                return;
            }
            if (!weixinGroup.getSysid().contains(sysid)) {
                logger.error("企业微信消息队列发送失败,sysid不合法！" + sysid);
                return;
            }
            WeixinQueueMsgRequest request = new WeixinQueueMsgRequest();
            request.setKey(weixinGroup.getGroupKey());
            String msgtype = msgJsonObject.getString("msgtype");
            String userAccountList = msgJsonObject.getString("userAccount");
            if (StringUtils.isNotEmpty(userAccountList)) {
                List<String> accountlist = Arrays.asList(userAccountList.split(","));
                LdapResponse<List<LdapEhrEmpDto>> resp = iFeignLdapService.getUserList(LdapEhrEmpSearchDto.builder().badgeList(accountlist).build());
                if (Objects.isNull(resp) || CollectionUtils.isEmpty(resp.getData())) {
                    logger.error("企业微信消息队列发送失败,未找到人员信息{}！", userAccountList);
                    return;
                }
                //不同类型构造方式不一样
                if (StringUtils.equals(msgtype, "markdown")) {
                    request.setMsgtype("markdown");
                    StringBuilder useridContent = new StringBuilder();
                    resp.getData().forEach(u -> {
                        if (Objects.nonNull(u.getOaUserId())) {
                            useridContent.append("<@").append(u.getOaUserId()).append(">");
                        }
                    });
                    request.setContent(msgJsonObject.getString("content") + useridContent);
                } else {
                    request.setContent(msgJsonObject.getString("content"));
                    List<String> mobilelist = resp.getData().stream()
                            .map(LdapEhrEmpDto::getMobile)
                            .filter(Strings::isNotBlank)
                            .collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(mobilelist)) {
                        logger.error("企业微信消息队列发送失败,查询后mobilelist为空！" + userAccountList);
                        return;
                    }
                    request.setMentionedMobileList(mobilelist);
                }
            }
            if (StringUtils.equals(msgtype, "markdown")) {
                request.setMsgtype("markdown");
            } else if (StringUtils.isNotEmpty(msgJsonObject.getString("all"))) {
                //markdown不支持@所有人
                List<String> mobilelist = request.getMentionedMobileList() == null ? new ArrayList<>() : request.getMentionedMobileList();
                mobilelist.add("@all");
                request.setMentionedMobileList(mobilelist);
            }

            if (StringUtils.isEmpty(request.getContent())) {
                request.setContent(msgJsonObject.getString("content"));
            }

            String json = JSONObject.toJSONString(request);
            logger.info("企业微信消息队列发送请求报文:" + json);

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//            JSONObject jsonob = JSONObject.parseObject(json);
            HttpEntity<String> formEntity = new HttpEntity<>(json, headers);
            ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, formEntity, String.class);
            logger.info("企业微信消息队列发送返回原始报文:" + postForEntity.getBody());
            if ((HttpStatus.OK).equals(postForEntity.getStatusCode())) {
                String res = postForEntity.getBody();
                JSONObject resjson = JSONObject.parseObject(res);
                if ("0".equals(resjson.getString("code"))) {
                    logger.info("企业微信消息队列发送发送成功。");
                } else {
                    logger.info("企业微信消息队列发送发送失败。res=" + res);
                }
            }
        } catch (Exception e) {
            logger.error("gateway.queue.shortmsg.weixin，消费消息队列异常", e);
        }
    }
}
